package com.mhy.tvcontrol

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.os.Parcelable
import android.util.Log
import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.ArrayAdapter
import android.widget.Button
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class DeviceListActivity : AppCompatActivity() {

    companion object {
        var EXTRA_DEVICE_ADDRESS = "device_address"
    }

    private val TAG = "DeviceListActivity"

    private var mBtAdapter: BluetoothAdapter? = null

    private var mNewDevicesArrayAdapter: ArrayAdapter<String?>? = null
    private var mPairedDevicesArrayAdapter: ArrayAdapter<String>? = null
    private var newlstDevices: MutableList<String?> = ArrayList()

    private val mDeviceClickListener =
        OnItemClickListener { adapterView, v, arg2, arg3 ->
            mBtAdapter?.cancelDiscovery()
            val info = (v as TextView).text.toString()
            val address = info.substring(info.length - 17)
            val intent = Intent()
            intent.putExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS, address)
            this@DeviceListActivity.setResult(-1, intent)
            finish()
        }

    private val mReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent) {
            val action = intent.action
            if (BluetoothDevice.ACTION_FOUND == action) {
                val device =
                    intent.getParcelableExtra<Parcelable>(BluetoothDevice.EXTRA_DEVICE) as BluetoothDevice?
                if (device!!.bondState != 12) {
                    val str = """
                    ${device.name}
                    ${device.address}
                    """.trimIndent()
                    if (newlstDevices.indexOf(str) == -1) {
                        newlstDevices.add(str)
                        mNewDevicesArrayAdapter!!.notifyDataSetChanged()
                    }
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {
                setProgressBarIndeterminateVisibility(false)
                setTitle("选择设备")
                if (mNewDevicesArrayAdapter!!.count == 0) {
                    mNewDevicesArrayAdapter!!.add("none_found")
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(5)
        setContentView(R.layout.devices_list)
        actionBar?.setBackgroundDrawable(ColorDrawable(0xff33bb77.toInt()))
// 返回箭头（默认不显示）
        actionBar?.setDisplayHomeAsUpEnabled(true);

// 左侧图标点击事件使能
        actionBar?.setHomeButtonEnabled(true);

// 使左上角图标(系统)是否显示
        actionBar?.setDisplayShowHomeEnabled(false);

// 显示标题
        actionBar?.setDisplayShowTitleEnabled(true);
        setTitle("配对 key:1234")
        setResult(0)
        (findViewById<Button>(R.id.button_scan)).setOnClickListener { v ->
            doDiscovery()
            v.setVisibility(View.GONE)
        }
        newlstDevices.clear()
        mPairedDevicesArrayAdapter = ArrayAdapter(this, R.layout.device_name)
        mNewDevicesArrayAdapter = ArrayAdapter<String?>(this, R.layout.device_name, newlstDevices)
        val pairedListView: ListView = findViewById(R.id.paired_devices) as ListView
        pairedListView.setAdapter(mPairedDevicesArrayAdapter)
        pairedListView.setOnItemClickListener(mDeviceClickListener)
        val newDevicesListView: ListView = findViewById(R.id.new_devices) as ListView
        newDevicesListView.setAdapter(mNewDevicesArrayAdapter)
        newDevicesListView.setOnItemClickListener(mDeviceClickListener)
        registerReceiver(mReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        registerReceiver(
            mReceiver,
            IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        )
        mBtAdapter = BluetoothAdapter.getDefaultAdapter()
        val pairedDevices = mBtAdapter!!.getBondedDevices()
        if (pairedDevices.size > 0) {
            findViewById<TextView>(R.id.title_paired_devices).setVisibility(View.VISIBLE)
            for (device in pairedDevices) {
                mPairedDevicesArrayAdapter!!.add(
                    """
                    ${device.name}
                    ${device.address}
                    """.trimIndent()
                )
            }
            return
        }
        mPairedDevicesArrayAdapter!!.add("none_paired")
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mBtAdapter != null) {
            mBtAdapter!!.cancelDiscovery()
        }
        unregisterReceiver(mReceiver)
    }

    fun doDiscovery() {
        Log.d(TAG, "doDiscovery()")
        setProgressBarIndeterminateVisibility(true)
        setTitle("正在扫描...")
        findViewById<TextView>(R.id.title_new_devices).setVisibility(View.VISIBLE)
        if (mBtAdapter?.isDiscovering==true) {
            mBtAdapter?.cancelDiscovery()
        }
        mBtAdapter!!.startDiscovery()
    }

}
